#!/usr/bin/perl
#copyright Ian Baker 2007

use Device::SerialPort;
use Time::HiRes qw (time usleep);

$if0 = new Device::SerialPort('/dev/ttyS0', 0);

$if0->baudrate(19200);
$if0->parity("odd");
$if0->databits(8);
$if0->stopbits(2);
$if0->handshake('none');

die "$!" unless $if0->write_settings;

$if1 = new Device::SerialPort('/dev/ttyS1', 0);

$if1->baudrate(19200);
$if1->parity("odd");
$if1->databits(8);
$if1->stopbits(2);
$if1->handshake('none');

die "$!" unless $if1->write_settings;

my @sensors = (7);

my ($read_count, @reads);
# clear it off.
while(1) {
foreach my $addr (@sensors) {
    foreach my $ct (0..4) {
        my $t1 = time();
        $if1->write(chr($addr));
        my ($count, $in);
        foreach(1..40) {
  	  ($count, $in) = $if1->read(255);
  	  last if $count;
#  	  print "rep\n";
        }
	my $t2 = time();
#	next unless( ord($in) > 9);
	print "$addr: " . join(',', unpack('C*', $in)) . " / $count " . ($t2 - $t1) . "\n";
	usleep (25000);
        $read_count++;
        push @reads, unpack('C*', $in);
        if($read_count == 1000) {
          my $sum;
          foreach(@reads) {
            $sum += $_;
          }
          my $avg = $sum / scalar(@reads);
          $read_count = 0;
          @reads = ();
          if($avg > 3.78) {
            $if0->write(chr(33));
            print "*"
          } else {
            $if0->write(chr(32));
          }
          print "$avg\n";
        }
    }
}
}
